<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in qfactoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="workerOrderstatus">
        <el-select v-model="queryParams.workerOrderstatus" placeholder="请选择" clearable>
          <el-option v-for="dict in orderStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="bomCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--<el-form-item label="订单日期">
        <el-date-picker
          v-model="daterangeOrderDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleWorkerOrder"
                   v-hasPermi="['order:workorder:edit']">创建半成品工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="printFactoryWorkorder"
                   v-hasPermi="['order:workorder:list']">导出分产订单数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="border-card" v-model="activeName">
      <el-tab-pane label="分厂订单（明细）" name="detail">
        <el-table v-loading="loading" border :data="workerOrderList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="订单类型" align="center" prop="workerOrdertype">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.workerorder_type" :value="scope.row.workerOrdertype" />
            </template>
          </el-table-column>
          <el-table-column label="订单日期" align="center" prop="orderDate" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.orderDate!=null">{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
              <span v-else>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单合同号" align="center" prop="contractCode" />
          <el-table-column label="客户名称" align="center" prop="customName" />
          <el-table-column label="单据编号" align="center" prop="orderCode" />
          <el-table-column label="产品名称" align="center" prop="bomName" />
          <el-table-column label="产品编码" align="center" prop="bomCode" />
          <el-table-column label="规格型号" align="center" prop="bomStandard" />
          <el-table-column label="产品单位" align="center" prop="productUnit" />
          <el-table-column label="产品数量" align="center" prop="planNum" />
          <!--<el-table-column label="分厂名称" align="center" prop="factoryName" />-->
          <el-table-column label="班组名称" align="center" prop="teamName" />
          <el-table-column label="订单状态" align="center" prop="workerOrderstatusDesc" />
          <el-table-column label="生产进度" align="center" prop="progress">
           <!--<template slot-scope="scope">
              {{scope.row.finishedCount/scope.row.planNum}}
            </template>-->
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePrint(scope.row)"
                v-hasPermi="['order:workorder:edit']">打印工单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-tab-pane>
      <el-tab-pane label="分厂订单（产品系列）" name="series">
        <el-table v-loading="loading"
                  border
                  row-key="rowKey"
                  :data="workerOrderGroupList"
                  lazy
                  :load="loadGroupChild"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="订单类型" align="center" prop="workerOrdertype" width="100">
            <template scope="scope">
              <div v-if="scope.row.bomLevel != null && scope.row.bomLevel != '0'">
                <el-tag effect="dark" :type="bomLevelType(scope.row)">{{scope.row.bomLevel}}</el-tag>
              </div>
              <div v-else>{{scope.row.workerOrdertype}}</div>
            </template>
          </el-table-column>
          <el-table-column label="订单日期" align="center" prop="orderDate" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.orderDate!=null">{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
              <span v-else>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单预计交期" align="center" prop="orderPlanFinishDate"  width="100" />
          <el-table-column label="排产开始日期" align="center" prop="planStartDate"  width="100" />
          <el-table-column label="排产完成日期" align="center" prop="planFinishDate"  width="100" />
          <el-table-column label="订单合同号" align="center" prop="contractCode" width="120px" />
          <el-table-column label="客户名称" align="center" prop="customName" />
          <el-table-column label="单据编号" align="center" prop="orderCode" width="120"/>
          <el-table-column label="产品系列" align="center" prop="productSeriesName" width="120" />
          <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
          <el-table-column label="产品编码" align="center" prop="productCode" width="100" />
          <el-table-column label="物料名称" align="center" prop="bomName" width="120" :show-overflow-tooltip="true" />
          <el-table-column label="物料编码" align="center" prop="bomCode" width="100"/>
          <el-table-column label="规格型号" align="center" prop="bomStandard" width="180" />
          <el-table-column label="产品单位" align="center" prop="productUnit" />
          <el-table-column label="班组名称" align="center" prop="teamName" />
          <el-table-column label="订单状态" align="center" prop="orderStatusDesc" />
          <el-table-column label="产品数量" align="center" prop="orderNum" />
          <el-table-column label="排产数量" align="center" prop="planNum"  width="80"/>
          <el-table-column label="材料库存" align="center" prop="storeNum"  width="80"/>
<!--          <el-table-column label="采样数量" align="center" prop="sampleNum" />-->
<!--          <el-table-column label="排产数量" align="center" prop="planNum" width="80"/>-->
          <el-table-column label="已完工数量" align="center" prop="finishedNum" width="120"/>
          <el-table-column label="已入库数量" align="center" prop="instockNum" width="120"/>
          <el-table-column label="金蝶入库量" align="center" prop="kingdeeInstockNum" width="120"/>
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePrint(scope.row)"-->
<!--                         v-hasPermi="['order:workorder:edit']">打印工单</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
        <pagination v-show="groupTotal > 0" :total="groupTotal" :page.sync="groupQueryParams.pageNum" :limit.sync="groupQueryParams.pageSize"
                    @pagination="querySeriesGroupList" />
      </el-tab-pane>
    </el-tabs>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" :close-on-click-modal ="false" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row :gutter="5">

          <el-col :span="12">
            <el-form-item label="产品名称：" prop="id"  v-model="form.id">
              <!--<el-select v-model="form.bomId" placeholder="请选择" filterable clearable @change="changeproduct">
                <el-option v-for="item in bominfoList" :key="item.bomId" :label="item.bomName" :value="item.bomId"></el-option>
              </el-select>-->
              <GridSelect
                  title="选择"
                  labelName = 'bomName'
                  labelValue = 'id'
                  :value = "form.id"
                  :limit="1"
                  size="small"
                  @getValue="getValue"
                  :columns="[
                    {
                      prop: 'bomCode',
                      label: '物料编码'
                    },{
                      prop: 'bomName',
                      label: '物料名称'
                    },{
                      prop: 'factoryName',
                      label: '产地'
                    },{
                      prop: 'teamName',
                      label: '班组'
                    }
                    ]"
                    :searchs="[
                    {
                      prop: 'bomCode',
                      label: '物料编码'
                    },{
                      prop: 'bomName',
                      label: '物料名称'
                    }
                  ]"
                  dataListUrl="/basic/materialinfo/list"
                  entityBeanName="smMaterialInfo"
                  queryEntityUrl="/basic/materialinfo/getMaterialInfo">
              </GridSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分厂名称" prop="factoryId">
              <el-select v-model="form.factoryId" placeholder="请选择" filterable clearable @change="changefactory">
                <el-option v-for="item in factoryList" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班组" prop="teamId">
              <el-select v-model="form.teamId" placeholder="请选择" filterable clearable>
                <el-option v-for="item in teamList" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品数量" prop="workerOrdernum">
                <el-input-number v-model="form.workerOrdernum" placeholder="请输入产品数量" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <el-table v-loading="loading"
        style="width: 100%"
        :data="materialinfoList"
        row-key="id"
        border
        lazy
        :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="子项物料编码" align="center" prop="bomCode" />
        <el-table-column label="物料名称" align="center" prop="bomName">
        </el-table-column>
        <el-table-column label="规格型号" align="center" prop="bomStandard" />
        <el-table-column label="物料属性" align="center" prop="bomAttribute" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.bom_attribute" :value="scope.row.bomAttribute" />
          </template>
        </el-table-column>
        <el-table-column label="BOM版本" align="center" prop="bomVersion" />
        <el-table-column label="单位" align="center" prop="bomUnit" >
        </el-table-column>
      </el-table>
      <br />
      <br />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept,listFactory } from "@/api/system/dept";
import {
  listWorkorder,
  addWorkorder,
  printWorkOrder ,
  printFactoryWorkorder,
  querySeriesGroupList,
  querySeriesGroupChildList
} from "@/api/sm/order/workorder";
import GridSelect from '@/components/gridSelect'
import { getMaterialinfo,listChildren,listMaterialinfo } from "@/api/sm/basic/materialinfo";
import { listChildrenContainsStore } from "@/api/sm/basic/bominfo";
export default {
  name: "Orderinfo",
  dicts: ['order_status', 'worker_orderstatus', 'workerorder_type', 'bom_attribute'],
  data() {
    return {
      activeName: "detail",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 非多个禁用
      multiple1: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总条数
      groupTotal: 0,
      // 订单信息表格数据
      workerOrderList: [],
      workerOrderGroupList: [],
      materialinfoList: [],
      bominfoList: [],
      factoryList: [],
      qfactoryList: [],
      teamList: [],
      orderStatusList: [
        {
          "label": "待排产",
          "value": 0
        },
        {
          "label": "待领料",
          "value": 1
        },
        {
          "label": "待生产",
          "value": 10
        },
        {
          "label": "待完工",
          "value": 20
        },
        {
          "label": "待入库",
          "value": 30
        },
        {
          "label": "待发货",
          "value": 40
        },
        {
          "label": "完成",
          "value": 50
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      workeropen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: null,
        orderCode: null,
        productCode: null,
        productName: null,
        customName: null,
        orderDate: null,
        workerOrderstatus: null,
        workerConfirmstatus: null,
        factoryId: null,
        teamId: null,
      },
      groupQueryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      // 表单参数
      form: {
        workerOrdertype: 2,
        factoryId: null,
        factoryName: null,
        teamName: null,
        teamId: null,
        bomCode: null,
        bomName: null,
        bomStandard: null,
        workerOrdernum: null
      },
      // 表单校验
      rules: {
        planStartDate: [
          { required: true, message: "排产截止时间不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getQFactoryList();
    this.getFactoryList();
    this.getList();
  },
  components: {
    GridSelect
  },
  methods: {
    bomLevelType(row) {
      switch (row.bomLevel) {
        case "1":
          return "success";
        case "2":
          return "info";
        case "3":
          return "warning";
        case "4":
          return "danger";
        case "5":
          return "info";
        default:
          break;
      }
      return "success";
    },
    loadGroupChild(tree, treeNode, resolve) {
      console.log("延迟加载:", tree, treeNode);
      if (tree.bomLevel && tree.bomLevel == "0") {
        querySeriesGroupChildList({
          factoryId: tree.factoryId,
          teamId: tree.teamId,
          contractCode: tree.contractCode,
          productSeriesName: tree.productSeriesName,
          index: tree.index,
        }).then((res) => {   //getChildMenu是我们自己的调用后台的封装
          resolve(                            //resolve是组件的
            res.data  //根据自己的格式,将查到的子菜单数组填充
          )
        })
        return;
      }

      let data = {
        parentBomCode: tree.bomCode,
        productId: tree.productId,
        productCode: tree.productCode,
        orderCode: tree.orderCode,
        customName: tree.customName,
        // "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        planNum: tree.planNum ? tree.planNum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildrenContainsStore(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        if (res.data && res.data.length === 0) {
          this.$modal.msgError(`${tree.bomCode}|${tree.bomName}, 未加载到子项物料数据`);
        }
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },
    load(tree, treeNode, resolve) {
      listChildren({"parentBomCode":tree.bomCode}).then((res) => {   //getChildMenu是我们自己的调用后台的封装
          resolve(                            //resolve是组件的
              res.data  //根据自己的格式,将查到的子菜单数组填充
          )
      })
    },
    getValue(v) {
      getMaterialinfo(v).then(response => {
        this.form.factoryId = response.data.factoryId;
        this.getTeamList(this.form.factoryId);
        this.form.teamId=response.data.teamId;
        this.form.bomCode=response.data.bomCode;
        this.form.bomName=response.data.bomName;

        this.form.bomName=response.data.bomName;
        this.form.bomStandard=response.data.bomStandard;
        this.form.factoryName=response.data.factoryName;
        this.form.teamName=response.data.teamName;
        listMaterialinfo({"parentBomCode":response.data.bomCode}).then(response => {
            this.materialinfoList = response.rows;
        });
      });
     // this.userform.userIds = v;
    },
    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = `顺美医疗生产订单_${row.teamName}(${row.bomName}).xls`; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    printFactoryWorkorder() {
      this.loading = true;
      // const ids = row.id || this.ids;
      printFactoryWorkorder(this.queryParams).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = `顺美医疗生产订单_分产订单管理数据.xls`; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        this.loading = false;
      });
    },
    /** 查询订单信息列表 */
    getQFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.qfactoryList = response.data;
        this.queryParams.factoryId = this.qfactoryList[0].deptId;
        this.getTeamList(this.queryParams.factoryId);
        this.loading = false;
      });
    },
    changeteam() {
      this.loading = true;
      let teamId = this.form.teamId;
      let bomId = this.form.bomId;
      listAllBominfo({ "parentBomId": bomId, "teamId": teamId }).then(response => {
        let resultList = response.data;

        this.loading = false;
      });
    },
    factoryChange(){
      this.teamList = [];
      this.getTeamList(this.queryParams.factoryId);
    },
    changefactory() {
      this.loading = true;
      this.productId = null;
      this.getTeamList(this.form.factoryId);
      this.loading = false;
    },
    getFactoryList() {
      listDept({ "level": 2, "delFlag": 0 }).then(response => {
        this.factoryList = response.data;
      });
    },
    getTeamList(factoryId) {
      listDept({"parentId":factoryId, "level": 3, "delFlag": 0 }).then(response => {
        this.teamList = response.data;
      });
    },
    /** 查询订单信息列表 */
    getList() {
      if (this.activeName === "detail") {
        this.loading = true;
        listWorkorder(this.queryParams).then(response => {
          this.workerOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
        });
      } else {
        this.querySeriesGroupList();
      }
    },
    /** 查询订单信息列表 */
    querySeriesGroupList() {
      this.loading = true;
      let requestParam = {};
      Object.assign(requestParam, this.queryParams);
      Object.assign(requestParam, this.groupQueryParams);
      querySeriesGroupList(requestParam).then(response => {
        this.workerOrderGroupList = response.rows || [];
        this.groupTotal = response.total;
        this.loading = false;
      }).catch((error) => {
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workerOrdertype: 2,
        factoryId: null,
        teamId: null,
        bomId: null,
        workerOrdernum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.codes = selection.map(item => item.productCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /**执行分单操作 */
    handleWorkerOrder() {
      this.open = true;
      this.reset();
      this.title = "创建半成品工单";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if( this.form.workerOrdernum<=0){
            alert("请输入产品数量");
            return;
          }
         // this.bominfoList.map((item1, index) => {
          //   if (item1.bomId == this.form.bomId){
          //     this.form.bomCode=item1.bomCode;
          //     this.form.bomName=item1.bomName;
          //     this.form.bomVersion=item1.bomVersion;
          //     this.form.productId=this.form.bomId;
          //   }
          //  })
          //  this.factoryList.map((item2, index) => {
          //   if (item2.deptId == this.form.factoryId){
          //     this.form.factoryName=item2.deptName;
          //   }
          //  })
          //  this.teamList.map((item3, index) => {
          //   if (item3.teamId == this.form.teamId){
          //     this.form.teamName=item3.teamName;
          //     this.form.teamCode=item3.teamCode;
          //   }
          //  })
          addWorkorder(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
  }
};
</script>
<style lang="scss">
  .ceshi-content {
    .check_btn {
      display: flex;

      div {
        margin-right: 30px;
      }
  }
  .check_item {
    display: flex;
    margin-top: 30px;
  }
  .el-table .cell {
    white-space: nowrap;
  }
  .warning-row {
    background-color: rgba(227, 234, 232, 0.99) !important;
  }
  .warning-row2 {
    background-color: rgba(189, 231, 219, 0.99) !important;
  }

  /*.el-table__body .level2 {*/
  /*  background: #fdf5e6;*/
  /*}*/
  /*.el-table__body .level3 {*/
  /*  background: #f0f9eb;*/
  /*}*/
  /*.el-table__body .level4 {*/
  /*  background: #d2f6bf;*/
  /*}*/
  /*.el-table__body .level5 {*/
  /*  background: #adf188;*/
  /*}*/
}
</style>
